﻿@page "/login"
@inject HttpClient Http
@inject AuthenticationStateProvider AuthStateProvider
@inject ILocalStorageService LocalStorage
@inject NavigationManager NavigationManager
@inject IJSRuntime JsRuntime

<PageTitle>Login</PageTitle>
<EditForm Model="dto" OnSubmit="HandleLogin">
    <DataAnnotationsValidator />
    <div class="row">
        <div class="col-lg-4 offset-lg-4 pt-4 pb-4 border">
            <div class="mb-3 text-center">
                <h3>L O G I N</h3>
            </div>
            <div class="mb-3">
                <label>用户名</label>
                <input @bind="dto.UserName" class="form-control" placeholder="例如：felix.zhu" />
                <ValidationMessage For="() => dto.UserName" />
            </div>
            <div class="mb-3">
                <label>密码</label>
                <input @bind="dto.Password" type="password" class="form-control" placeholder="初始密码123" />
                <ValidationMessage For="() => dto.Password" />
            </div>
            <div class="mb-3 d-grid gap-2">
                <button type="submit" class="btn btn-primary">登 录</button>
            </div>
        </div>
    </div>
</EditForm>
@code {
    UserDto dto = new();
    async Task HandleLogin()
    {
        var result = await Http.PostAsJsonAsync("api/Login/Name", dto);
        var resultContent = await result.Content.ReadFromJsonAsync<ApiResponse<string>>();
        if (resultContent.Status)
        {
            var token= resultContent.Result;
            await LocalStorage.SetItemAsync("token", token);
            await AuthStateProvider.GetAuthenticationStateAsync();
            NavigationManager.NavigateTo("");
        }
        else
        {
            await JsRuntime.InvokeVoidAsync("alert", "登录失败，请重试！");
            dto.Password = "";
        }
    }
}
